package com.star.bookkeeping;

import android.os.Bundle;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import androidx.appcompat.app.AppCompatActivity;

import com.star.bookkeeping.controller.JavaScriptInterface;
import com.star.bookkeeping.database.BillDBHelper;

public class MainActivity extends AppCompatActivity {
    private BillDBHelper mDBHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView webView = findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
//        webSettings.setUseWideViewPort(true);
//        webSettings.setLoadWithOverviewMode(true);
        // 设置WebChromeClient
        webView.setWebChromeClient(new MyWebChromeClient());
        // 初始化 JavaScript 接口
        mDBHelper = BillDBHelper.getInstance(this);
        mDBHelper.openReadLink();
        mDBHelper.openWriteLink();

        JavaScriptInterface jsInterface = new JavaScriptInterface(this);
        jsInterface.initWebView(webView); // 添加 JavaScript 接口

        webView.loadUrl("file:///android_asset/index.html");
    }

    // 自定义WebChromeClient类
    private class MyWebChromeClient extends WebChromeClient {

        // 重写onConsoleMessage方法
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            String message = consoleMessage.message();
            int lineNumber = consoleMessage.lineNumber();
            String sourceId = consoleMessage.sourceId();

            Log.d("WebViewConsole", "Message: " + message + ", Line Number: " + lineNumber + ", Source ID: " + sourceId);

            // 返回true表示消息已被处理，否则返回false
            return true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDBHelper.closeLink();
    }
}